package com.t235.gc.zuul.rbac;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.context.RequestContext;
import com.t235.gc.AjaxResult;
import com.t235.gc.JwtTokenUtils;
import com.t235.gc.entity.SysMenu;
import com.t235.gc.feign.auth.MenuRemoteClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class RbacService {
    @Resource
    private MenuRemoteClient menuRemoteClient;
    @Resource
    private ObjectMapper objectMapper;

    public boolean hasPermission(String requestUri, String roles, String token) {
        List<SysMenu> sysMenus = this.queryByRoleNames(roles, token);
        if (log.isDebugEnabled()) {
            log.debug("meuns:{},{}", sysMenus.size(), sysMenus);
        }
        return hasPerm(requestUri, sysMenus);
    }

    private boolean hasPerm(String requestUri, List<SysMenu> menus) {
        for (SysMenu menu : menus) {
            if (menu.getInterfaceurl().equals(requestUri)) {
                return true;
            } else {
                if(menu.getMenuChildren() != null && !menu.getMenuChildren().isEmpty()) {
                    if(hasPerm(requestUri, menu.getMenuChildren())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private List<SysMenu> queryByRoleNames(String roleNames, String token) {
        RequestContext.getCurrentContext().addZuulRequestHeader(JwtTokenUtils.TOKEN_HEADER, JwtTokenUtils.TOKEN_PREFIX + token);
        AjaxResult ajaxResult = menuRemoteClient.roleMenus(roleNames, JwtTokenUtils.TOKEN_PREFIX + token);
        List<SysMenu> sysMenus = objectMapper.convertValue(ajaxResult.getData(), new TypeReference<List<SysMenu>>() {});
        return sysMenus;
    }
}
